package com.rasenhund.android.grecorder.helper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.rasenhund.android.grecorder.common.Const;
import com.rasenhund.android.grecorder.dao.RecordDao;
import com.rasenhund.android.myutility.SqlUtil;

/**
 * データベース作成用Helperクラス
 */
public class DbHelper extends SQLiteOpenHelper{
    
    private static final String DATABASE_NAME = "senjou_db";
    
    public DbHelper(Context context){
        super(context, DATABASE_NAME, null, Const.getDatabaseVersion());
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(getCreateTableSql(RecordDao.TABLE_NAME));
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        if (oldVersion == 1 && newVersion == 2) {

            // 0.9.4 > 0.9.5 : 対戦人数、戦闘ランク、ポイント、メモ、集計対象外フラグを追加
            db.execSQL(SqlUtil.getAlterTableSql_Integer(RecordDao.TABLE_NAME,
                    RecordDao.Columns.VERSUS));
            db.execSQL(SqlUtil.getAlterTableSql_Integer(RecordDao.TABLE_NAME,
                    RecordDao.Columns.POINT));
            db.execSQL(SqlUtil.getAlterTableSql_Integer(RecordDao.TABLE_NAME,
                    RecordDao.Columns.RANK_CD));
            db.execSQL(SqlUtil.getAlterTableSql_Text(RecordDao.TABLE_NAME, RecordDao.Columns.MEMO));
            db.execSQL(SqlUtil.getAlterTableSql_Integer(RecordDao.TABLE_NAME,
                    RecordDao.Columns.EXCLUDE_FLG));

        }

    }

    /**
     * Create Table 取得
     * 
     * @param tableName
     * @return SQL
     */
    private String getCreateTableSql(String tableName) {

        String sSql = "";

        // @formatter:off
        sSql = "CREATE TABLE " + tableName + 
                "(" + 
                    RecordDao.Columns.ROW_ID +  " integer primary key autoincrement" + 
                    ", " + RecordDao.Columns.STAGE_CD + " integer default 0" + 
                    ", " + RecordDao.Columns.CATEGORY_CD + " integer default 0" + 
                    ", " + RecordDao.Columns.RESULT_CD + " integer default 0" + 
                    ", " + RecordDao.Columns.INSERT_DATE + " text" + 
                    // 0.9.4 > 0.9.5 : 対戦人数、戦闘ランク、ポイント、メモ、集計対象外フラグを追加
                    ", " + RecordDao.Columns.VERSUS + " integer default 0" + 
                    ", " + RecordDao.Columns.POINT + " integer default 0" + 
                    ", " + RecordDao.Columns.RANK_CD + " integer default 0" + 
                    ", " + RecordDao.Columns.MEMO + " text default ''" +
                    ", " + RecordDao.Columns.EXCLUDE_FLG + " integer default 0" + 
                ")";
        // @formatter:on

        return sSql;

    }

}
